<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { addGroup, groupDetail, updateGroup } from '#/api/iot/device/group';

const emit = defineEmits<{ reload: [] }>();

const [BasicModal, modalApi] = useVbenModal({
  onClosed: handleClosed,
  onConfirm: handleSubmit,
  onOpenChange: handleOpenChange,
});

const [BasicForm, formApi] = useVbenForm({
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
        showCount: true,
        maxlength: '30',
      },
      fieldName: 'groupName',
      label: '群组名称',
      rules: 'required',
    },
    {
      component: 'Textarea',
      fieldName: 'groupDesc',
      label: '群组描述',
      // rules: 'required',
    },
  ],
  showDefaultActions: false,
  commonConfig: {
    labelWidth: 80,
  },
});

const modalType = ref<string>('');
const title = computed(() => {
  if (modalType.value === 'addRoot') {
    return $t('pages.common.addRootGroup');
  } else if (modalType.value === 'addSub') {
    return $t('pages.common.addSubGroup');
  } else {
    return $t('pages.common.editGroup');
  }
});
async function handleOpenChange(open: boolean) {
  if (!open) {
    return;
  }
  modalApi.modalLoading(true);
  const { id, type } = modalApi.getData();
  modalType.value = type;
  if (id && modalType.value === 'edit') {
    const res = await groupDetail(id);
    formApi.setValues(res);
  }
  modalApi.modalLoading(false);
}

async function handleSubmit() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = await formApi.getValues();
    const { id, parentId, type } = modalApi.getData();
    data.id = id;
    data.parentId = parentId;
    if (type === 'edit') {
      await updateGroup(data);
    } else {
      data.parentId = id;
      await addGroup(data);
    }
    emit('reload');
    handleClosed();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleClosed() {
  modalApi.close();
  await formApi.resetForm();
}
</script>

<template>
  <BasicModal
    :close-on-click-modal="false"
    :fullscreen-button="false"
    :title="title"
  >
    <div class="flex flex-col gap-[12px]">
      <BasicForm />
    </div>
  </BasicModal>
</template>
